<script setup lang="ts">
import PageSearch from "@/components/page-search/page-search.vue";
import PageModal from "@/components/page-modal/page-modal.vue";
import PageContent from "@/components/page-content/page-content.vue";
import searchConfig from "@/views/main/system/role/config/search.config";
import contentConfig from "@/views/main/system/role/config/content.config";
import modalConfig from "@/views/main/system/role/config/modal.config";
import usePageContent from "@/hooks/usePageContent";
import usePageModal from "@/hooks/usePageModal";
import useSystemStore from "@/stores/modules/main/system/system";
import { ref, useTemplateRef, nextTick } from "vue";
import { ElTree } from "element-plus";
import {mapMenuListToIds} from "@/utils/mapMenus";

/**
 * 新增角色时，清空菜单列表
 */
const newCallback = () => {
  nextTick(() => {
    treeRef.value?.setCheckedKeys([]);
  })
}

/**
 * 编辑角色时，回显角色所拥有的菜单列表
 * @param itemData 当前编辑的角色信息
 */
const editCallback = (itemData: any) => {
  nextTick(() => {
    const menuIds = mapMenuListToIds(itemData.menuList)
    treeRef.value?.setCheckedKeys(menuIds);
  })
}

const { contentRef, handleQueryClick, handleResetClick } = usePageContent();
const { modalRef, handleNewClick, handleEditClick } = usePageModal(newCallback, editCallback); // editCallback 必须在 usePageModal() 方法前初始化

const systemStore = useSystemStore();
const menuList = systemStore.menuList;

const treeRef = useTemplateRef<InstanceType<typeof ElTree>>("treeRef");
const treeInfo = ref({});

/**
 * 选择某菜单节点的回调函数
 * @param node 传递给 data 属性的数组中该节点所对应的对象
 * @param checked 树目前的选中状态对象
 */
const handleElTreeCheck = (node: any, checked: any) => {
  const menuList = [...checked.checkedKeys, ...checked.halfCheckedKeys];
  treeInfo.value = { menuList };
};

</script>

<template>
  <div class="role">
    <page-search
      :searchConfig="searchConfig"
      :query-click="handleQueryClick"
      @reset-click="handleResetClick"
    />
    <page-content
      ref="contentRef"
      :content-config="contentConfig"
      @new-data-click="handleNewClick"
      @edit-data-click="handleEditClick"
    />
    <page-modal ref="modalRef" :modal-config="modalConfig" :treeInfo="treeInfo">
      <template #menuList>
        <el-tree
          ref="treeRef"
          :data="menuList"
          show-checkbox
          node-key="id"
          :props="{ children: 'children', label: 'name' }"
          @check="handleElTreeCheck"
        />
      </template>
    </page-modal>
  </div>
</template>

<style scoped></style>
